package cn.zzzhy.spider;

import cn.zzzhy.util.HttpClientUtil;
import org.joda.time.DateTime;

/**
 * @author zzzhy
 * @since 16/2/29 下午1:33
 */
public class DownloadTool implements Runnable {

    private Thread thread = null;
    private boolean isRun = true;

    @Override
    public void run() {
        String url;
        while (isRun) {
            synchronized (DownloadPool.download) {
                while (DownloadPool.download.isEmpty()) {
                    try {
                        DownloadPool.download.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("当前下载池大小:++++++" + DownloadPool.download.size());
                url = DownloadPool.download.iterator().next();
                DownloadPool.download.remove(url);
                DownloadPool.download.notifyAll();
            }
            System.out.println("正在处理url:" + url);
            conduct(url);
        }
    }

    private void conduct(String url) {
        String fileName = DateTime.now().toString("yyyyMMddHHmmss") + "-" + DownloadPool.fileNo.getAndAdd(1);
        HttpClientUtil.downloadFile(url, fileName);
    }

    public void download() {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
        } else {
            DownloadPool.download.notifyAll();
        }
    }

    public void stop() {
        isRun = false;
        thread = null;
    }
}
